#include <tj_bill_list_output.h>
#include "pub_var.h"
#include <QMessageBox>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>

namespace tj_bill_list_output
{

void fill_item_detail(QJsonArray &jsa_val, QJsonArray jsa_tmp, int row)
{
    QJsonObject jot;

    for(int count = 0; count < jsa_tmp.size(); count++ )
    {

        jot.insert("val", jsa_tmp[count].toObject().value("index").toString());
        jot.insert("row", row);
        jot.insert("col", 1);
        jsa_val << jot;

        jot.insert("val", jsa_tmp[count].toObject().value("center_code").toString());
        jot.insert("row", row);
        jot.insert("col", 2);
        jsa_val << jot;

        jot.insert("val", jsa_tmp[count].toObject().value("his_name").toString());
        jot.insert("row", row);
        jot.insert("col", 3);
        jsa_val << jot;

        jot.insert("val", jsa_tmp[count].toObject().value("specs").toString());
        jot.insert("row", row);
        jot.insert("col", 4);
        jsa_val << jot;

        jot.insert("val", jsa_tmp[count].toObject().value("price").toString());
        jot.insert("row", row);
        jot.insert("col", 5);
        jsa_val << jot;

        jot.insert("val", jsa_tmp[count].toObject().value("qty").toString());
        jot.insert("row", row);
        jot.insert("col", 6);
        jsa_val << jot;

        jot.insert("val", jsa_tmp[count].toObject().value("tot_cost").toString());
        jot.insert("row", row);
        jot.insert("col", 7);
        jsa_val << jot;

        row ++;
    }
}

double fill_fee_detail(QJsonArray &jsa_val , QJsonArray jsa_tmp, int row)
{
    QJsonObject jot;

    double ret = 0;

    for(int count = 0; count < jsa_tmp.size(); count++ )
    {

        ret += jsa_tmp[count].toObject().value("tot_cost").toString().toDouble();

        jot.insert("val", jsa_tmp[count].toObject().value("index").toString());
        jot.insert("row", row);
        jot.insert("col", 1);
        jsa_val << jot;

        jot.insert("val", jsa_tmp[count].toObject().value("invoice_no").toString());
        jot.insert("row", row);
        jot.insert("col", 2);
        jsa_val << jot;

        jot.insert("val", jsa_tmp[count].toObject().value("setl_id").toString());
        jot.insert("row", row);
        jot.insert("col", 3);
        jsa_val << jot;

        jot.insert("val", jsa_tmp[count].toObject().value("tot_cost").toString());
        jot.insert("row", row);
        jot.insert("col", 4);
        jsa_val << jot;

        jot.insert("val", jsa_tmp[count].toObject().value("own_cost").toString());
        jot.insert("row", row);
        jot.insert("col", 5);
        jsa_val << jot;

        jot.insert("val", jsa_tmp[count].toObject().value("pay_cost").toString());
        jot.insert("row", row);
        jot.insert("col", 6);
        jsa_val << jot;

        jot.insert("val", jsa_tmp[count].toObject().value("pub_cost").toString());
        jot.insert("row", row);
        jot.insert("col", 7);
        jsa_val << jot;

        row ++;
    }

    return ret;
}

//clinic_code， 是否输出挂号诊查费, 是否打印输出
bool bill_list_output(QString clinic_code, bool reg_check_fee, bool print_out)
{
    //qrm = new QSqlQuery(pub::db_m);
    //static
    QSqlQuery *qro = new QSqlQuery(pub::db_o);
    //qrot = new QSqlQuery(pub::db_o);

    QString sq;
    QString his_name, his_code, center_code, unit, specs, mdtrt_id;
    double price;
    int qty ;
    int index = 1;

    QJsonDocument doc4clear;
    QJsonObject fee_content;
    QJsonArray fee_content_list;
    QJsonObject patient_info;
    QJsonArray item_list;
    QJsonObject item_single;

    //费用明细列标题
    fee_content["invoice_no"] = "发票号";
    fee_content["mdtrt_id"] = "就诊ID";
    fee_content["setl_id"] = "医保结算ID";
    fee_content["tot_cost"] = "合计费用";
    fee_content["pay_cost"] = "账户";
    fee_content["pub_cost"] = "统筹";
    fee_content["own_cost"] = "现金";
    fee_content["index"] = "序号";
    fee_content_list << fee_content;
    fee_content = doc4clear.object();

    //项目明细列表
    item_single["his_name"] = "项目名称";
    item_single["his_code"] = "item_code";
    item_single["center_code"] = "icd编码";
    item_single["specs"] = "规格";
    item_single["qty"] = "数量";
    item_single["index"] = "序号";
    item_single["tot_cost"] = "金额";
    item_single["price"] = "价格";
    item_list << item_single;

    //查询挂号信息
    sq = " select card_no,reg_date,name,idenno,sex_code,rela_phone,reglevl_code,"
         " pact_code, dept_name, diag_fee, own_cost, pub_cost, pay_cost, "
            //" to_char(reg.birthday, 'yyyy-mm-dd') bd"
            " birthday, invoice_no"
            " from fin_opr_register"
            " where clinic_code = '" + clinic_code + "' and valid_flag = '1'";

    qDebug()<<"查询挂号记录："<<sq<<"\n";
    qro->exec(sq);

    if(qro->next())
    {

        patient_info["name"] = qro->value("name").toString();
        patient_info["card_no"] = qro->value("card_no").toString();
        patient_info["reg_date"] = qro->value("reg_date").toDateTime().toString("yyyy-MM-dd HH:mm:ss");
        patient_info["idenno"] = qro->value("idenno").toString();
        patient_info["sex_code"] = qro->value("sex_code").toString();
        patient_info["rela_phone"] = qro->value("rela_phone").toString();
        patient_info["pact_code"] = qro->value("pact_code").toString();
        patient_info["reglevl_code"] = qro->value("reglevl_code").toString();
        patient_info["dept_name"] = qro->value("dept_name").toString();

        QDate birth = qro->value("birthday").toDate();
        double age = birth.daysTo(qro->value("reg_date").toDate());
        patient_info["age"] = QString::number(age/365.25 , 'f', 1);

    }
    else
    {
        QMessageBox::information(NULL, "注意", "找不到有效的挂号记录！" );
        return false;
    }

    qDebug()<<"patient_info : "<<patient_info<<"\n";
    //需要计算挂号费
    if(reg_check_fee)
    {
        //非医保挂号费，可以从挂号记录提取费用信息
        fee_content["invoice_no"] = qro->value("invoice_no").toString();
        fee_content["tot_cost"] = QString::number(qro->value("diag_fee").toDouble(), 'f', 2);

        //提取挂号包含的收费项目信息
        sq = " select comp.fixmedins_hilist_name, reg.fee_code_his, reg.fee_code_center,"
             " reg.fee_code_his, undrug.unit_price, undrug.stock_unit"
             " from fin_opr_regfeeitem reg "
             " left join fin_com_undruginfo undrug on undrug.item_code = reg.fee_code_his"
             " left join fin_com_compare comp on comp.fixmedins_hilist_id = reg.fee_code_his"
             " where reg.reg_level = '" + qro->value("reglevl_code").toString() + "'";
        sq += " and undrug.valid_state = '1' ";

        qro->exec(sq);
        qDebug()<<"提取挂号项目明细："<<sq<<"\n";

        while(qro->next())
        {
            his_name = qro->value("fixmedins_hilist_name").toString();
            his_code = qro->value("fee_code_his").toString();
            center_code = qro->value("fee_code_center").toString();
            //item_name = qro->value("fee_code_his").toString();
            unit = qro->value("stock_unit").toString();
            price = qro->value("unit_price").toDouble();
            qty = 1;

            item_single["his_name"] = his_name;
            item_single["his_code"] = his_code;
            item_single["center_code"] = center_code;
            item_single["tot_cost"] = QString::number(price * qty, 'f', 2);
            item_single["unit"] = unit;
            item_single["price"] = QString::number(price, 'f', 2);
            item_single["qty"] = QString::number(qty);
            item_single["specs"] = "-";
            item_single["index"] = QString::number(index);

            item_list << item_single;

            index++;

        }
        qDebug()<<"挂号项目 item_list : "<<item_list<<"\n";

    }

    //统计票据信息
    if(patient_info["pact_code"].toString() == "2")
    {
        //提取医保收费信息

        //防止出现医保挂号现金结算，输出时未选择诊察费，无法获取就诊ID的情况
        //在这里强制提取一下挂号记录关联的就诊ID
        sq = " select  mdtrt_id from fin_ipr_siinmaininfo "
             " where inpatient_no = '%1' and valid_flag = '1' and balance_no = '0'";
        sq = sq.arg(clinic_code);
        qro->exec(sq);
        qro->next();
        mdtrt_id = qro->value(0).toString();

        //因为有医保号现金开药的情况，有些费用在 siinmaininfo 中没有记录。
        //所以费用提取以 fin_com_invoiceinfo 为准
        sq = "";
        if(reg_check_fee)
        {
            //挂号记录 fin_opb_invoiceinfo 中没有，只能从 siinmaininfo 提取
            sq = " select  tot_cost, own_cost, pub_cost, pay_cost,  "
                 " invoice_no,mdtrt_id, setl_id  ,balance_no"
                 " from fin_ipr_siinmaininfo "
                 " where inpatient_no = '%1' and valid_flag = '1' and balance_no = '0'"
                 " union ";
        }
        sq += "select fin.tot_cost, fin.own_cost, si.pub_cost, si.pay_cost, "
             " fin.invoice_no, si.mdtrt_id, si.setl_id, si.balance_no "
             " from fin_opb_invoiceinfo fin"
             " left join fin_ipr_siinmaininfo si on fin.invoice_no = si.invoice_no"
             " where fin.clinic_code = '%1' and fin.cancel_flag = '1'"
                //" group by invoice_no, mdtrt_id, setl_id"
                //" having max(trans_type) = '1'"
                " order by balance_no";

        sq = sq.arg(clinic_code);

        qDebug()<<"提取医保收费信息:"<<sq<<"\n";
        qro->exec(sq);

        int count = 0;
        while(qro->next())
        {
            count++;
            fee_content["index"] = QString::number(count);
            fee_content["invoice_no"] = qro->value("invoice_no").toString();
            fee_content["mdtrt_id"] = qro->value("mdtrt_id").toString();
            fee_content["setl_id"] = qro->value("setl_id").toString();
            fee_content["tot_cost"] = QString::number(qro->value("tot_cost").toDouble(), 'f', 2);
            fee_content["pay_cost"] = QString::number(qro->value("pay_cost").toDouble(), 'f', 2);
            fee_content["pub_cost"] = QString::number(qro->value("pub_cost").toDouble(), 'f', 2);
            fee_content["own_cost"] = QString::number(qro->value("own_cost").toDouble(), 'f', 2);

            fee_content_list << fee_content;

        }
    }
    else
    {
        //现金
        if(reg_check_fee)
        {
            //直接使用已经提取过的信息医保
            fee_content_list << fee_content;
        }
        sq = "select tot_cost, invoice_no from fin_opb_invoiceinfo "
             " where clinic_code = '" + clinic_code + "' and cancel_flag = '1'" ;
        qro->exec(sq);
        qDebug()<<"查询收费记录："<<sq<<"\n";
        int count = 0;
        while(qro->next())
        {
            count++;
            fee_content["index"] = QString::number(count);
            fee_content["tot_cost"] = QString::number(qro->value("tot_cost").toDouble(), 'f', 2);
            fee_content["invoice_no"] = qro->value("invoice_no").toString();
            fee_content_list << fee_content;
        }

    }

    qDebug()<<"收费记录明细："<<fee_content_list<<"\n";

    //查询费用项目明细
    sq = "select item_name, specs, item_code, center_code,price_unit,unit_price,"
         " (qty / pack_qty) qty, (own_cost) tot_cost"
         " from fin_opb_feedetail"
         " where clinic_code = '%1' and cancel_flag = '1'"
         " order by mo_order";
    sq = sq.arg(clinic_code);
    //sq += " group by item_name, specs, item_code, center_code,price_unit";

    qDebug()<<"查询费用项目明细"<<sq<<"\n";

    qro->exec(sq);

    QJsonDocument d;
    QJsonArray jsa_val;    //表格数据
    QJsonObject jot;  // 临时json

    qro->exec(sq);
    while(qro->next())
    {
        item_single["his_name"] = qro->value("item_name").toString();
        item_single["his_code"] = qro->value("item_code").toString();
        item_single["center_code"] = qro->value("center_code").toString();
        item_single["specs"] = qro->value("specs").toString();
        item_single["unit"] = qro->value("price_unit").toString();
        item_single["qty"] = QString::number(qro->value("qty").toInt());
        item_single["index"] = QString::number(index);
        item_single["tot_cost"] = QString::number(qro->value("tot_cost").toDouble(), 'f', 2);
        item_single["price"] = QString::number(qro->value("unit_price").toDouble(), 'f', 2);
        //item_single["tot_cost"] = qro->value("tot_cost").toDouble();
        //item_single["price"] = qro->value("unit_price").toDouble() ;
        item_list << item_single;
        index++;
        //qDebug()<<"item_single:"<<item_single<<"\n";
    }

    //表格标题
    jot.insert("val", pub::hos_name);
    jot.insert("row", 1);
    jot.insert("col", 1);
    jsa_val << jot;

    int cur_row = 3;
    QString tmp;
    tmp = "姓名：" + patient_info["name"].toString();

    if(patient_info["sex_code"].toString() == "F")
    {
        tmp += "  性别：女";
    }
    else
    {
        tmp += "  性别：男";
    }

    tmp += "  年龄：" + patient_info["age"].toString();
    tmp += "  诊室：" + patient_info["dept_name"].toString();
    tmp += "  病志号：" + patient_info["card_no"].toString();

    jot.insert("val", tmp);
    jot.insert("row", cur_row);
    jot.insert("col", 1);
    jsa_val << jot;
    cur_row++;

    tmp = "挂号时间：" + patient_info["reg_date"].toString();
    if(patient_info["pact_code"] == "2")
    {
        //
        tmp += "  医保挂号就诊ID：" + mdtrt_id;
    }
    else
    {
        tmp += "  现金挂号";
    }

    tmp += "  门诊号：" + clinic_code;

    jot.insert("val", tmp);
    jot.insert("row", cur_row);
    jot.insert("col", 1);
    jsa_val << jot;
    cur_row++;

    double tot_cost = fill_fee_detail(jsa_val, fee_content_list, cur_row);

    cur_row += fee_content_list.size();

    tmp = "打印时间：" + QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
    tmp += "              ";
    tmp += "本次门诊合计金额：" + QString::number(tot_cost, 'f', 2) ;

    //需要合并的区域
    //merge_range : [{ range : string }]
    QJsonArray jsa_merge;    //合并区域
    jot = d.object();
    jot.insert("range", QString("A%1:G%1").arg(QString::number( cur_row)));
    jsa_merge << jot;

    jot.insert("val", tmp);
    jot.insert("row", cur_row);
    jot.insert("col", 1);
    jsa_val << jot;
    cur_row++;

    fill_item_detail(jsa_val, item_list, cur_row);

    QJsonArray jsa_rng;    //表格区域
    jot = d.object();
    QString rg = QString("A3:G%1").arg(QString::number( cur_row + item_list.size() - 1));
    jot.insert("range", rg);
    jsa_rng << jot;

    QJsonObject jo; //打印参数
    jo.insert("excel_model", "/sheets/bill_list.xls");
    jo.insert("cell_value", jsa_val);
    jo.insert("grid_range", jsa_rng);
    jo.insert("merge_range", jsa_merge);

    if(!print_out)
    {
        jo.insert("process_mode", "s"); //只保存，不打印
    }

    pub::printOutExcel(jo);

    return true;
}

}
